package com.acenodie.acenodieopenglturorial.filter;

import android.opengl.Matrix;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class VideoDrawFilter {
	private static final String TAG = "VideoMagicFilter";

	private OutputFilter mOutputFilter;
	private FloatBuffer mGLCubeBuffer;
	private FloatBuffer mGLTextureBuffer;
	private int mDisplayWidth = 0, mDisplayHeight = 0;
	private int mOutputWidth = 0, mOutputHeight = 0;
	private boolean mIsMirror;

	public VideoDrawFilter() {


		mOutputFilter = new OutputFilter();

		mGLCubeBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.CUBE.length * 4).order(ByteOrder.nativeOrder())
				.asFloatBuffer();
		mGLCubeBuffer.put(TextureRotationUtil.CUBE).position(0);
		mGLTextureBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.TEXTURE_NO_ROTATION.length * 4)
				.order(ByteOrder.nativeOrder()).asFloatBuffer();
		mGLTextureBuffer.put(TextureRotationUtil.getRotation(Rotation.NORMAL, false, true)).position(0);
	}

	public void initFilter() {
		mOutputFilter.init();
	}
	
	public void setMirror(boolean mirror) {
//		mIsMirror = mirror;
		if (mirror) {
			mGLTextureBuffer.put(TextureRotationUtil.getRotation(Rotation.NORMAL, true, true)).position(0);
		} else {
			mGLTextureBuffer.put(TextureRotationUtil.getRotation(Rotation.NORMAL, false, true)).position(0);
		}
	}

	public void onFilterChanged(int displayWidth, int displayHeight, int outputWidth, int outputHeight) {
		if (mDisplayWidth == displayWidth && mDisplayHeight == displayHeight && mOutputWidth == outputWidth
				&& mOutputHeight == outputHeight) {
			return;
		}
		mDisplayWidth = displayWidth;
		mDisplayHeight = displayHeight;
		mOutputWidth = outputWidth;
		mOutputHeight = outputHeight;
		mOutputFilter.onOutputSizeChanged(mOutputWidth, mOutputHeight);
		mOutputFilter.onDisplaySizeChanged(mDisplayWidth, mDisplayHeight);
	}
	
	public void onDrawFrame(final int textureId) {
		mOutputFilter.onDrawFrame(textureId, mGLCubeBuffer, mGLTextureBuffer);
	}


	public synchronized void destroy() {
		if (mOutputFilter != null) {
			mOutputFilter.destroy();
			mOutputFilter = null;
		}
		
		if (mGLCubeBuffer != null) {
			mGLCubeBuffer.clear();
			mGLCubeBuffer = null;
		}
		if (mGLTextureBuffer != null) {
			mGLTextureBuffer.clear();
			mGLTextureBuffer = null;
		}
	}

	private void filpMatrix(float[] matrix) {
		Matrix.translateM(matrix, 0, 0.5f, 0.5f, 0.0f);
		Matrix.scaleM(matrix, 0, 1.0f, -1.0f, 1.0f);
		Matrix.translateM(matrix, 0, -0.5f, -0.5f, 0.0f);
	}
}
